package com.stone.name.space.parser;


import com.stone.scan.OptimizerScanner;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.beans.factory.xml.XmlReaderContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.util.StringUtils;
import org.w3c.dom.Element;
import java.util.LinkedList;
import java.util.List;

/**
 * <p>Created with IntelliJ IDEA. </p>
 * <p>User: Stony </p>
 * <p>Date: 2016/7/1 </p>
 * <p>Time: 14:05 </p>
 * <p>Version: 1.0 </p>
 */
public class OptimizerAnnotationBeanDefinitionParser implements BeanDefinitionParser {

    public static final String OPTIMIZER_BEAN_LIST = "G_OPTIMIZER_BEAN_LIST";
    private List<Class> classes;

    @Override
    public BeanDefinition parse(Element element, ParserContext parserContext) {
        XmlReaderContext readerContext = parserContext.getReaderContext();
        OptimizerScanner optimizerScanner = new OptimizerScanner(readerContext.getRegistry());

        try {
            String basePackage = element.getAttribute("base-package");
            classes = optimizerScanner.scanBeanClass(StringUtils.tokenizeToStringArray(basePackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        RootBeanDefinition beanDefinition = new RootBeanDefinition();
        beanDefinition.setBeanClass(LinkedList.class);
        beanDefinition.setLazyInit(false);
        if (classes != null) {
            beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(0, classes);
        }
        parserContext.getRegistry().registerBeanDefinition(OPTIMIZER_BEAN_LIST, beanDefinition);
        return beanDefinition;
    }
}
